package parser.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Page;
import org.jsoup.Jsoup;
import parser.Parse;
import utils.CrawlerUtils;

import java.io.IOException;
import java.net.MalformedURLException;

public class JDParser implements Parse {

    @Override
    public void parse(Page page) {
        page.setId(CrawlerUtils.getUUID());
        page.setGoodid(CrawlerUtils.getGoodsId(page.getUrl()));
        try {
            page.setSource(CrawlerUtils.getDomain(page.getUrl()));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        String title = Jsoup.parse(page.getContent()).select("div[class='sku-name']").text().trim();
        page.setTitle(title);

        //获取商品图片url
        String imgUrl = "https:" + Jsoup.parse(page.getContent()).select("img[id='spec-img']").attr("data-origin");
        page.setImgurl(imgUrl);

        //获取售价
        try {
            page.setPrice(CrawlerUtils.parsePrice("https://p.3.cn/prices/mgets?skuIds=J_" + page.getGoodid()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取评论数量和好评率
        try {
            CrawlerUtils.getComment(page);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取参数
        JSONObject intro = CrawlerUtils.getPara(page);
        JSONObject detail = null;
        try {
            detail = CrawlerUtils.getDetail(page);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray info = new JSONArray();
        info.add(intro);
        info.add(detail);
        JSONObject json = new JSONObject();
        json.put("产品参数", info);
        page.setPara(json.toJSONString());
    }


}
